import type { AxiosResponse, InternalAxiosRequestConfig } from './types';
import qs from 'qs';
import { SUCCESS_CODE, TRANSFORM_REQUEST_DATA } from '@/constants';
import { objToFormData } from './utils';
const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  if (config.method === 'post' && config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
    config.data = qs.stringify(config.data, { arrayFormat: 'brackets' });
  } else if (
    TRANSFORM_REQUEST_DATA &&
    config.method === 'post' &&
    config.headers['Content-Type'] === 'multipart/form-data' &&
    !(config.data instanceof FormData)
  ) {
    config.data = objToFormData(config.data);
  }

  // if (config.method === "get" && config.params) {
  //   const queryString = qs.stringify(config.params);
  //   config.url += `?${queryString}`;
  //   config.params = {};
  // }

  return config;
};

const defaultResponseInterceptors = (response: AxiosResponse) => {
  if (response?.config?.responseType === 'blob') {
    // 如果是文件流，直接过
    return response;
  } else if (response?.data?.code === SUCCESS_CODE) {
    return response?.data;
  } else {
    console.warn('异常', response?.data);
  }
};

export { defaultResponseInterceptors, defaultRequestInterceptors };
